
//
//  JTNetInfoViewController.swift
//  JT Center
//
//  Created by 林殊 on 2021/5/27.
//  Copyright © 2021 J&T Express. All rights reserved.
//

import UIKit
import WebKit

class JTNetInfoViewController: UIViewController {
    
    private var _url: URL?
    
    @objc
    var url: URL? {
        get { return _url }
        set {
            _url = newValue
            if newValue == nil { return }
            let request = getRequest()
            webView.load(request)
        }
    }
    
    lazy var webView: WKWebView = {
        let config = WKWebViewConfiguration()
        let preferences = WKPreferences()
        config.preferences = preferences
        let web = WKWebView(frame: .zero, configuration: config)
        web.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
        web.addObserver(self, forKeyPath: #keyPath(WKWebView.title), options: .new, context: nil)
        web.navigationDelegate = self
        
        return web
    }()
    
    private lazy var progressView: UIProgressView = {
        let progressView = UIProgressView()
        progressView.tintColor = UIColor(red: 230.0/255.0, green: 38.0/255.0, blue: 44.0/255.0, alpha: 1)   // 进度条颜色
        progressView.trackTintColor = .white // 进度条背景色
        return progressView
    }()
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    init(_ url: URL?) {
        super.init(nibName: nil, bundle: nil)
        self.url = url
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "信息监测"
        if #available(iOS 11.0, *) {
            webView.scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        webView.scrollView.showsVerticalScrollIndicator = false
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(doDismiss))
    }
    
    @objc
    func doDismiss() {
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        var saveInset: UIEdgeInsets = .zero
        
        if #available(iOS 11.0, *) {
            saveInset = UIApplication.shared.keyWindow?.safeAreaInsets ?? .zero
        }
        
        let mainBounds = UIScreen.main.bounds
        progressView.frame = CGRect(x: 0, y: saveInset.top + 44, width: mainBounds.width, height: 1)
        webView.frame = CGRect(x: 0, y: saveInset.top + 44, width: mainBounds.width, height: mainBounds.height - saveInset.top - 44)
    }
    
    override func loadView() {
        
        view = UIView()
        
        view.addSubview(webView)
        view.addSubview(progressView)
    }
    
    
    override func observeValue(forKeyPath keyPath: String?,
                               of object: Any?,
                               change: [NSKeyValueChangeKey : Any]?,
                               context: UnsafeMutableRawPointer?) {
        
        guard let theKeyPath = keyPath, object as? WKWebView == webView else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }
         
        
        if theKeyPath == #keyPath(WKWebView.estimatedProgress) {
            progressView.alpha = 1.0
            if webView.estimatedProgress > Double(progressView.progress) {
                progressView.setProgress(Float((webView.estimatedProgress) ), animated: true)
            }
            if (webView.estimatedProgress) >= 1.0 {
                UIView.animate(withDuration: 1.0, delay: 0.1, options: .curveEaseOut, animations: {
                    self.progressView.alpha = 0
                }, completion: { _ in
                    self.progressView.setProgress(0.0, animated: false)
                })
            }
        }
    }
    
    func getRequest() -> URLRequest {
        return URLRequest(url: url!)
    }
}
 
extension JTNetInfoViewController: WKNavigationDelegate {

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.isOpaque = true
    }
}

extension JTNetInfoViewController: WKUIDelegate {
    func webView(_ webView: WKWebView,
                 createWebViewWith configuration: WKWebViewConfiguration,
                 for navigationAction: WKNavigationAction,
                 windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)
        }
        return nil
    }
}
